<template>
  <div v-if="poem" class="poetry-detail-view min-h-screen">
    <!-- 背景装饰 -->
    <div class="fixed inset-0 pointer-events-none">
      <div class="absolute top-20 left-10 w-32 h-20 bg-accent-yellow opacity-10 rounded-circle animate-bounce"></div>
      <div class="absolute top-40 right-20 w-24 h-16 bg-secondary-turquoise opacity-10 rounded-circle animate-bounce" style="animation-delay: 1s;"></div>
      <div class="absolute bottom-40 left-1/4 w-40 h-24 bg-primary-coral opacity-10 rounded-circle animate-bounce" style="animation-delay: 2s;"></div>
    </div>
    
    <div class="relative z-10 max-w-4xl mx-auto px-6 py-8">
      <!-- 返回按钮 -->
      <div class="mb-8">
        <button 
          @click="$router.back()"
          class="btn-icon focus-ring"
        >
          <span class="text-white text-xl">←</span>
        </button>
      </div>
      
      <!-- 古诗标题区域 -->
      <div class="bg-white rounded-card p-8 shadow-card mb-8">
        <div class="flex items-start justify-between mb-6">
          <div class="flex-1">
            <h1 class="text-4xl md:text-5xl font-bold text-text-primary mb-4">
              {{ poem.title }}
            </h1>
            
            <div class="flex items-center space-x-4 mb-4">
              <div class="flex items-center space-x-2">
                <img 
                  :src="`/images/poet_${getAuthorImageName(poem.author)}_0.jpg`" 
                  :alt="poem.author"
                  class="w-10 h-10 rounded-circle"
                  @error="handleImageError"
                />
                <div>
                  <div class="text-lg font-semibold text-text-primary">{{ poem.author }}</div>
                  <div class="text-sm text-text-secondary">{{ poem.dynasty }}代</div>
                </div>
              </div>
              
              <div class="flex items-center space-x-2">
                <button 
                  @click="toggleFavorite"
                  class="w-10 h-10 rounded-circle flex items-center justify-center transition-all"
                  :class="isFavorited 
                    ? 'bg-accent-yellow text-white' 
                    : 'bg-gray-100 text-gray-400 hover:bg-accent-yellow hover:text-white'"
                >
                  <span class="text-lg">★</span>
                </button>
                
                <button 
                  @click="markAsLearned"
                  class="px-4 py-2 rounded-pill text-sm font-semibold transition-all"
                  :class="isLearned 
                    ? 'bg-accent-green text-white' 
                    : 'bg-primary-coral text-white hover:bg-primary-orange'"
                >
                  {{ isLearned ? '✓ 已学习' : '标记学习' }}
                </button>
                
                <button 
                  @click="markAsMastered"
                  class="px-4 py-2 rounded-pill text-sm font-semibold transition-all"
                  :class="isMastered 
                    ? 'bg-accent-green text-white' 
                    : 'bg-secondary-turquoise text-white hover:bg-secondary-skyBlue'"
                >
                  {{ isMastered ? '✓ 已掌握' : '标记掌握' }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 古诗原文 -->
      <div class="bg-white rounded-card p-8 shadow-card mb-8">
        <h2 class="text-2xl font-bold text-text-primary mb-6">原文</h2>
        <div class="text-xl md:text-2xl leading-relaxed text-text-primary font-medium">
          <p v-for="(line, index) in getLines(poem.original_text)" :key="index" class="mb-3">
            <span 
              v-for="(char, charIndex) in line" 
              :key="charIndex"
              class="hover:bg-accent-yellow hover:bg-opacity-30 rounded px-1 cursor-pointer transition-colors"
              @click="showWordTooltip(char, $event)"
            >
              {{ char }}
            </span>
          </p>
        </div>
      </div>
      
      <!-- 拼音标注 -->
      <div class="bg-white rounded-card p-8 shadow-card mb-8">
        <h2 class="text-2xl font-bold text-text-primary mb-6">拼音</h2>
        <div class="text-lg leading-relaxed text-text-secondary">
          <p v-for="(pinyinLine, index) in getPinyinLines(poem.pinyin)" :key="index" class="mb-3">
            {{ pinyinLine }}
          </p>
        </div>
      </div>
      
      <!-- 创作背景 -->
      <div class="bg-white rounded-card p-8 shadow-card mb-8">
        <h2 class="text-2xl font-bold text-text-primary mb-4">创作背景</h2>
        <p class="text-lg text-text-secondary leading-relaxed">
          {{ poem.creative_background }}
        </p>
      </div>
      
      <!-- 背景故事 -->
      <div class="bg-white rounded-card p-8 shadow-card mb-8">
        <h2 class="text-2xl font-bold text-text-primary mb-4">背景故事</h2>
        <div class="text-lg text-text-secondary leading-relaxed">
          <p class="mb-4">{{ getFirstParagraph(poem.background_story) }}</p>
          <p v-if="hasMoreStory" class="text-primary-coral cursor-pointer hover:underline" @click="toggleFullStory">
            {{ showFullStory ? '收起' : '展开阅读' }}
          </p>
          <p v-if="showFullStory" class="mt-4">{{ getRemainingStory(poem.background_story) }}</p>
        </div>
      </div>
      
      <!-- 关键词汇解释 -->
      <div v-if="poem.key_words && poem.key_words.length > 0" class="bg-white rounded-card p-8 shadow-card mb-8">
        <h2 class="text-2xl font-bold text-text-primary mb-6">关键词汇</h2>
        <div class="grid gap-4">
          <div 
            v-for="word in poem.key_words" 
            :key="word.word"
            class="p-4 bg-background-cream rounded-input"
          >
            <div class="flex items-center justify-between mb-2">
              <h3 class="text-lg font-bold text-text-primary">{{ word.word }}</h3>
              <span class="text-sm text-text-secondary">{{ word.pinyin }}</span>
            </div>
            <p class="text-text-secondary">{{ word.explanation }}</p>
          </div>
        </div>
      </div>
      
      <!-- 意境描述 -->
      <div class="bg-white rounded-card p-8 shadow-card mb-8">
        <h2 class="text-2xl font-bold text-text-primary mb-4">意境描述</h2>
        <p class="text-lg text-text-secondary leading-relaxed">
          {{ poem.artistic_conception }}
        </p>
      </div>
    </div>
    
    <!-- 词汇解释气泡 -->
    <WordTooltip 
      v-if="showTooltip" 
      :word="tooltipWord" 
      :explanation="tooltipExplanation"
      :position="tooltipPosition"
      @close="hideTooltip"
    />
  </div>
  
  <div v-else class="poetry-detail-view min-h-screen flex items-center justify-center">
    <div class="text-center">
      <div class="animate-spin w-12 h-12 border-4 border-primary-coral border-t-transparent rounded-full mx-auto mb-4"></div>
      <p class="text-text-secondary">正在加载古诗...</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { usePoetryStore } from '@/stores/poetry'
import { useProgressStore } from '@/stores/progress'
import WordTooltip from '@/components/WordTooltip.vue'
import type { Poetry } from '@/types'

const route = useRoute()
const poetryStore = usePoetryStore()
const progressStore = useProgressStore()

// 响应式数据
const showFullStory = ref(false)
const showTooltip = ref(false)
const tooltipWord = ref('')
const tooltipExplanation = ref('')
const tooltipPosition = ref({ x: 0, y: 0 })

// 计算属性
const poemId = computed(() => parseInt(route.params.id as string))
const poem = computed(() => poetryStore.getPoetryById(poemId.value))
const isLearned = computed(() => progressStore.progress.learned_poems.includes(poemId.value))
const isMastered = computed(() => progressStore.progress.mastered_poems.includes(poemId.value))
const isFavorited = computed(() => progressStore.progress.favorites.includes(poemId.value))
const hasMoreStory = computed(() => {
  if (!poem.value) return false
  const paragraphs = poem.value.background_story.split('\n').filter(p => p.trim())
  return paragraphs.length > 1
})

// 初始化数据
onMounted(async () => {
  if (!poetryStore.poetryCollection) {
    await poetryStore.loadPoetryData()
  }
})

// 获取作者头像名称
const getAuthorImageName = (author: string): string => {
  const nameMap: Record<string, string> = {
    '李白': 'libai',
    '杜甫': 'dufu',
    '骆宾王': 'luobinwang',
    '孟浩然': 'default',
    '贺知章': 'default',
    '李绅': 'default',
    '杨万里': 'default',
    '白居易': 'default',
    '杜牧': 'default',
    '王之涣': 'default',
    '王维': 'default',
    '王昌龄': 'default',
    '贾岛': 'default',
    '张继': 'default',
    '孟郊': 'default',
    '王安石': 'default',
    '苏轼': 'default',
    '柳宗元': 'default',
    '文嘉': 'default'
  }
  
  return nameMap[author] || 'default'
}

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = '/images/icon_book_3.jpg'
}

// 获取古诗分行
const getLines = (text: string): string[] => {
  return text.split(/[，。！？]/).filter(line => line.trim()).map(line => line.trim())
}

// 获取拼音分行
const getPinyinLines = (pinyin: string): string[] => {
  return pinyin.split(/[，。！？]/).filter(line => line.trim()).map(line => line.trim())
}

// 获取第一段
const getFirstParagraph = (story: string): string => {
  const paragraphs = story.split('\n').filter(p => p.trim())
  return paragraphs[0] || story
}

// 获取剩余段落
const getRemainingStory = (story: string): string => {
  const paragraphs = story.split('\n').filter(p => p.trim())
  return paragraphs.slice(1).join(' ')
}

// 切换完整故事显示
const toggleFullStory = () => {
  showFullStory.value = !showFullStory.value
}

// 切换收藏状态
const toggleFavorite = () => {
  progressStore.toggleFavorite(poemId.value)
}

// 标记为已学习
const markAsLearned = () => {
  if (!isLearned.value) {
    progressStore.markPoemAsLearned(poemId.value)
  }
}

// 标记为已掌握
const markAsMastered = () => {
  if (!isMastered.value) {
    progressStore.markPoemAsMastered(poemId.value)
  }
}

// 显示词汇解释气泡
const showWordTooltip = (word: string, event: MouseEvent) => {
  if (!poem.value) return
  
  // 查找匹配的词汇解释
  const matchedWord = poem.value.key_words?.find(w => w.word.includes(word) || word.includes(w.word))
  if (matchedWord) {
    tooltipWord.value = matchedWord.word
    tooltipExplanation.value = matchedWord.explanation
    tooltipPosition.value = { x: event.clientX, y: event.clientY }
    showTooltip.value = true
  }
}

// 隐藏词汇解释气泡
const hideTooltip = () => {
  showTooltip.value = false
}
</script>

<style scoped>
.poetry-detail-view {
  background: linear-gradient(135deg, #FFFBF0 0%, #FFF4E6 100%);
}
</style>